package com.dongdong.config;


import com.dongdong.realm.LoginRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.mgt.DefaultFilter;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

@Configuration
public class ShiroConfig {

    @Bean
    public LoginRealm loginRealm() {
        LoginRealm loginRealm = new LoginRealm();
        loginRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return loginRealm;
    }


    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager() {

        return new DefaultWebSecurityManager(loginRealm());
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean() {
        ShiroFilterFactoryBean shiro = new ShiroFilterFactoryBean();
//        放到安全管理器
        shiro.setSecurityManager(defaultWebSecurityManager());
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
//        放行
        map.put("/login/**", DefaultFilter.anon.name());
        map.put("/js/**", DefaultFilter.anon.name());

//        退出登录
        map.put("/logout", DefaultFilter.logout.name());

//        拦截
        map.put("/**", DefaultFilter.authc.name());
        shiro.setFilterChainDefinitionMap(map);

        return shiro;
    }

    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {


        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
//      用什么加密  就用什么解密
//        指定加密方式
        matcher.setHashAlgorithmName("md5");
//        指定加密次数
        matcher.setHashIterations(7);
//        指定编码（是否存储为16进制）
        matcher.setStoredCredentialsHexEncoded(true);

        return matcher;
    }
}
